package uodm.server;

import java.io.IOException;
import java.security.Principal;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import uodm.shared.model.OfficeData;
import uodm.shared.rpc.UodmService;

import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class UodmServlet extends RemoteServiceServlet implements UodmService {

	@Override
	public List<OfficeData> getOfficeDataList() {
		Utils.logAccess(getThreadLocalRequest(), this.getClass().getName()
				+ "." + Utils.getCurrentMethodName());
		// String userEmail = getUserEmail();
		// HttpServletResponse resp = getThreadLocalResponse();
		// if (userEmail == null) {
		// try {
		// resp.sendRedirect(UserServiceFactory
		// .getUserService()
		// .createLoginURL(
		// Utils.getFullRequestUrl(getThreadLocalRequest())));
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// return null;
		// } else {
		// return Utils.ofy().load().type(OfficeData.class).list();
		return Utils.ofy().query(OfficeData.class).list();
		// }
	}

	@Override
	public void addOffice(OfficeData officeData) {
		Utils.logAccess(getThreadLocalRequest(), this.getClass().getName()
				+ "." + Utils.getCurrentMethodName());
		String userEmail = getUserEmail();
		HttpServletResponse resp = getThreadLocalResponse();
		if (userEmail == null) {
			try {
				resp.sendRedirect(UserServiceFactory
						.getUserService()
						.createLoginURL(
								Utils.getFullRequestUrl(getThreadLocalRequest())));
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			officeData.setCreatorEmail(userEmail);
			// Utils.ofy().save().entity(officeData);
			Utils.ofy().put(officeData);
		}
	}

	private String getUserEmail() {
		Principal p = getThreadLocalRequest().getUserPrincipal();
		if (p == null) {
			return null;
		} else {
			return p.getName();
		}
	}

}
